package org.lmind.example.util.text;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 占位符解析器
 * @author mian.liu
 *
 */
public class PlaceholderResolver {
	
	/** 默认的占位符前缀 */
	public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";

	/** 默认的占位符后缀 */
	public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";
	
	/** 占位符解析时使用的正则表达式 */
	private Pattern pattern;
	
	private int groupIndex;
	
	public PlaceholderResolver() {
		this(DEFAULT_PLACEHOLDER_PREFIX, DEFAULT_PLACEHOLDER_SUFFIX);
	}

	/**
	 * 
	 * @param placeholderPrefix 占位符前缀
	 * @param placeholderSuffix 占位符后缀
	 */
	public PlaceholderResolver(String placeholderPrefix, String placeholderSuffix) {
		this(Pattern.compile(Pattern.quote(placeholderPrefix) + "(.*?)" + Pattern.quote(placeholderSuffix)), 1);
	}
	
	/**
	 * 
	 * @param placeholder 占位符的正则表达式
	 */
	public PlaceholderResolver(Pattern placeholder, int groupIndex) {
		pattern = placeholder;
		this.groupIndex = groupIndex;
	}
	
	public Resolver resolver(String text) {
		return new Resolver(text);
	}
	
	public class Resolver {
		
		private String text;
		
		private Matcher matcher;
		
		private TextReplacement re = new TextReplacement();
		
		public Resolver(String text) {
			super();
			this.text = text;
			matcher = pattern.matcher(text);
		}
		
		public boolean next() {
			return matcher.find();
		}

		public String getKey() {
			return matcher.group(groupIndex);
		}

		public void replace(String replacement) {
			if (replacement == null)
				throw new IllegalArgumentException();
			re.add(matcher.start(), matcher.end(), replacement);
		}
		
		public String build() {
			return re.apply(text);
		}
	}
	
}
